package com.zr.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.zr.dao.UserDao;
import com.zr.model.Func;
import com.zr.model.Role;
import com.zr.model.User;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Repository("userDao")
public class UserDaoImpl<T> extends  BaseDaOImpl<T> implements UserDao<T> {

	public JSONArray getallfuns(int pid,String funcs) {
		JSONArray js = new JSONArray();
		StringBuffer sql = new StringBuffer();
		sql.append(" select * from func f ");
		sql.append(" where f.pid=:pid and f.fid IN ("+funcs+")");
		Query  query  =  this.getCurrentSession().createSQLQuery(sql.toString()).addEntity(Func.class);
		query.setInteger("pid",pid);
		List<Func>  fs = query.list();
		for (Func func : fs) {
			JSONObject j = new JSONObject();
			j.put("id", func.getFid());
			j.put("text",func.getFname());
			j.put("state",func.getFstate());
			JSONObject attr = new JSONObject();
			attr.put("furl", func.getFurl());
			j.put("attributes", attr);
			js.add(j);		
		}
		return js;
	}
	@Override
	public JSONArray getAllFunction(int pid,String funcs) {
		JSONArray   userfuncs  = this.getallfuns(pid,funcs);
		for (int i = 0; i < userfuncs.size(); i++) {
			  String state = userfuncs.getJSONObject(i).getString("state");
			  if("open".equals(state)){
				     continue;
			  }else{
				   int currentId = userfuncs.getJSONObject(i).getInt("id");
				   JSONArray   children  = this.getAllFunction(currentId,funcs);
				   userfuncs.getJSONObject(i).put("children", children);
			  }
		}return  userfuncs;
	}


}
